<template>
    <div class="anchorSelection" v-show="isShow">
        <div class="headers">
            <van-nav-bar title="主播选品" left-arrow @click-left="navLeftClick" />
            <!-- 筛选 -->
            <div style="" class="product_list_serch-text">
                <van-search class="product_list_serch1" placeholder="请输入主播部门" v-model="queryParams.deptName"
                    shape="round" clearable />
                <div class="product_list_serch2">
                    <img src="@/assets/revenue/icon_search.png" alt="" class="product_list-btn" @click="onSearch">
                </div>
            </div>
            <!-- 主播场次 -->
            <div class="session">
                <div :class="sessionIndex == index ? 'session_child_active' : 'session_child'"
                    v-for="(item, index) in sessionList" :key="index" @click="sessionClcik(index, item)">
                    {{ item.name }}
                </div>
            </div>
        </div>
        <div class="content">
            <div class="content_left">
                <div :class="anthorTypeIndex == index ? 'content_left_child_active' : 'content_left_child'"
                    v-for="(item, index) in anthorType" :key="index" @click="anthorTypeClcik(index)">{{ item }}
                </div>
            </div>
            <div class="content_right">
                <template v-for="(it, index) in anchorList" :key="index">
                    <div class="content_right_titte" v-show="anthorTypeIndex == 0 || anthorTypeIndex == index + 1">{{
                        it.label }}</div>
                    <div class="content_right_div" v-show="anthorTypeIndex == 0 || anthorTypeIndex == index + 1">
                        <div class="shell" v-for="(item) in it.children" :key="item.id"
                            :style="{ width: computedWidth(item) }">
                            <div :class="coreId == item.id ? 'items_top_avtive' : 'items_top'"
                                v-if="item.type !== 'apprentice'" @click="coreClick(item, it.children)"
                                :style="{ width: item.label.length >= 5 ? '120px' : '80px' }">
                                {{ item.label }}
                                <img :src="coreId == item.id ? icon_below_blue : icon_below" alt=""
                                    v-if="item.children && item.children.length > 0">
                            </div>
                            <!-- 徒弟 -->
                            <div v-if="item.type == 'apprentice'"
                                :class="apprenticeIndex == items.id ? 'apprenticeAvtive' : 'apprentice'"
                                v-for="items in item.datas" :key="items.id" @click="apprenticeClick(items)">
                                {{ items.label }}
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        <div class="bottom">
            <div class="cancel" @click="navLeftClick">取消</div>
            <div class="submit" @click="submit">
                <template v-if="loading">
                    <van-loading type="spinner" size="24px" color="#fff" > 执行中...</van-loading>
                </template>
                <template v-else> 
                    保存
                </template> 
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, defineProps, watch } from "vue";
import { deptTree, queryUserIdByDeptId, changeCoreIsAudit } from '@/api/productList/index'
import { showFailToast, showConfirmDialog } from "vant";
const icon_below_blue = new URL("@/assets/revenue/icon_below_blue.png", import.meta.url).href
const icon_below = new URL("@/assets/revenue/icon_below.png", import.meta.url).href
const porps = defineProps({
    isShow: { default: () => false },
    isChange: { default: {} },
    id: { default: () => '' },
    loading:{ default: () => false },
})
const emit = defineEmits([
    'goback',
    'onSubmit',
    'onChangeSubmit'
])
// 主播集合
const anchorList = ref()
// 选中主播id
const coreId = ref()
// 选中主播名称
const coreName = ref()
// 选中主播徒弟id
const apprenticeIndex = ref()
// 选中主播徒弟名称
const apprenticeName = ref()
// 选中id
const coreDeptId = ref()

// 查询
const queryParams = ref<{
    deptName?: string,
}>({
    deptName: undefined,
})
// 主播场次
const sessionList = ref<{ name: string, value: string }[]>([
    { name: '平播', value: '平播' },
    { name: '打榜', value: '打榜' },
    { name: '活动', value: '活动' },
    { name: '大货', value: '大货' },
])
// 主播场次下标
const sessionIndex = ref()
// 主播场次value
const session = ref('')
// 主播类型
const anthorType = ref<any>([])
// 主播类型下标
const anthorTypeIndex = ref(0)

watch(() => porps.isShow, async (v) => {
    if (v) {
        await getAnchor()
    }
})
watch(() => porps.isChange, async (v: any) => {
    if (Object.keys(v).length > 0) {
        const sessionIndexs = sessionList.value.findIndex((item) => item.name === v.liveType);
        // 主播场次下标
        sessionIndex.value = sessionIndexs;
        // 主播场次名称
        session.value = v.liveType;
        const res = await queryUserIdByDeptId({ userId: v.coreId })
        // 0 主播 1 徒弟
        if (res.data.layer == 0) {
            // 主播id
            coreId.value = res.data.deptId
            // 主播名称
            coreName.value = v.coreName
            // 
            coreDeptId.value = res.data.deptId
        } else if (res.data.layer == 1) {
            // 徒弟名称
            apprenticeName.value = v.coreName
            // 徒弟id
            apprenticeIndex.value = res.data.deptId
            // 主播id
            coreId.value = res.data.parentId
            //
            coreDeptId.value = res.data.deptId

            anchorList.value.forEach((element) => {
                element.children.forEach((item: any, index: number) => {
                    if (item.id == res.data.parentId) {
                        // 获取行得最后一个下标
                        const nextIndex = computedIndex(element.children, index)
                        // 新增子元素
                        element.children.splice(nextIndex + 1, 0,
                            {
                                type: 'apprentice',
                                datas: item.children
                            }
                        )
                    }
                })
            })
        }

    }
})

/** 计算弹性盒子宽度 */
const computedWidth = (item: any) => {
    if (item.type == 'apprentice') {
        return '100%'
    } else {
        return item.label.length >= 5 ? '50%' : 'calc(100% / 3)'
    }
}

/** 主播徒弟点击 */
const apprenticeClick = (item: any) => {
    apprenticeIndex.value = item.id
    apprenticeName.value = item.label
    coreDeptId.value = item.id
}
/** 清空所有徒弟子元素 */
const cheartApprentice = () => {
    anchorList.value.forEach((item: any) => {
        if (item.children) {
            item.children.forEach((vals: any, indexs: number) => {
                if (vals.type == 'apprentice') {
                    item.children.splice(indexs, 1)
                }
            });
        }
    })
}
/** 主播点击 */
const coreClick = (item: any, data: any) => {
    coreId.value = item.id
    coreName.value = item.label
    // 清除所有展示得子元素
    cheartApprentice()
    // 获取当前元素下标
    const index = data.findIndex((val: any) => val.id == item.id)
    // 获取行得最后一个下标
    const nextIndex = computedIndex(data, index)
    // 新增子元素
    if (item.children) {
        data.splice(nextIndex + 1, 0,
            {
                type: 'apprentice',
                datas: item.children
            }
        )
    }
    // 删除徒弟选中留存的状态
    apprenticeIndex.value = undefined
    apprenticeName.value = undefined
    coreDeptId.value = item.id
}
// 头部导航点击事件
const navLeftClick = () => {
    emit('goback')
    clear()
}

/** 主播场次点击事件 */
const sessionClcik = (index: number, item: { name: string, value: string }) => {
    sessionIndex.value = index
    session.value = item.value
}
/** 主播类型点击事件 */
const anthorTypeClcik = (index: number) => {
    anthorTypeIndex.value = index
}

/** 筛选 */
const onSearch = async () => {
    // 主播id 清空
    coreId.value = undefined
    // 主播name 清空
    coreName.value = undefined
    // 主播类型下标 清空
    anthorTypeIndex.value = 0
    // 主播场次下标 清空
    sessionIndex.value = 0
    // 徒弟id清空
    apprenticeIndex.value = undefined
    // 徒弟名称清空
    apprenticeName.value = undefined
    await getAnchor()
}
/** 获取二维数组中某一个值得行索引 */
const findValueIndex = (matrix, target) => {
    for (let i = 0; i < matrix.length; i++) {
        for (let j = 0; j < matrix[i].length; j++) {
            if (matrix[i][j] === target) {
                return i;
            }
        }
    }
    return null;
}
/** 根据主播下标获取当前行最后一个下标 */
const computedIndex = (data: any, indexs: number) => {
    var arr: any = []
    var width: number = 0;
    var arrs: any = []
    data.forEach((element, index) => {
        if (element.label.length <= 4) {
            element.width = 3

        } else {
            element.width = 5
        }
        if (width + element.width <= 10) {
            arrs.push(index)
            width += element.width
        } else if (width + element.width > 10) {
            arr.push(arrs)
            width = 0
            arrs = []
            arrs.push(index)
            width += element.width
        }
        if (index == data.length - 1) {
            arr.push(arrs)
        }
    });
    const hangIndex: any = findValueIndex(arr, indexs)
    // 获取行得最后一个下标
    return arr[hangIndex][arr[hangIndex].length - 1]

}
/** 获取主播 */
const getAnchor = async () => {
    const response = await deptTree({ deptId: '1782395835898970113', ...queryParams.value })
    anthorType.value = ['全部', ...response.data.map(item => item.label.slice(0, 6))]
    response.data.forEach(item => {
        item.label = item.label.slice(0, 6)
        if (!item.children) {
            item.children = [
                {
                    label: item.label.slice(0, 6),
                    id: item.id,
                    parentId: item.id,
                    weight: 1
                }

            ]
        }
    })
    anchorList.value = response.data
}
/** 提交 */
const submit = async () => {
    if (!coreId.value) {
        showFailToast({
            message: '请选择主播',
            teleport: '.anchorSelection'
        })
    } else if (!session.value) {
        showFailToast({
            message: '请选择主播类型',
            teleport: '.anchorSelection'
        })
    } else {
        if (Object.keys(porps.isChange).length > 0) {
            const resFlag = await changeCoreIsAudit({
                id: porps.id,
                liveType: session.value,
                coreDeptId: coreDeptId.value
            })
            // 重新送审
            if (resFlag) {
                showConfirmDialog({
                    message:
                        '将按照当前商品信息进行送审，是否确认提交？',
                })
                    .then(() => {
                        emit('onChangeSubmit', session.value, coreDeptId.value)
                        clear()
                    })
                    .catch(() => {
                        // on cancel
                    });
            } else {
                showConfirmDialog({
                    message:
                        '即将变更主播信息/直播类型，请确认',
                })
                    .then(() => {
                        emit('onChangeSubmit', session.value, coreDeptId.value)
                        clear()
                    })
                    .catch(() => {
                        // on cancel
                    });
            }
        } else {
            emit('onSubmit', apprenticeIndex.value || coreId.value, apprenticeName.value || coreName.value, session.value, coreDeptId.value)
            clear()
        }
    }

}
/** 清空缓存 */
const clear = async () => {
    // 主播id 清空
    coreId.value = undefined
    // 主播name 清空
    coreName.value = undefined
    // 主播类型下标 清空
    anthorTypeIndex.value = 0
    // 主播场次下标 清空
    sessionIndex.value = ''
    // 搜索清空
    queryParams.value.deptName = undefined
    // 徒弟清空
    apprenticeIndex.value = undefined
    // 徒弟名称清空
    apprenticeName.value = undefined
    // 清空徒弟
    cheartApprentice()
}
</script>
<script lang="ts">
export default { name: 'AnchorSelection' }
</script>
<style lang="less" scoped>
:deep(.van-nav-bar) {
    position: absolute !important;
    z-index: 6004 !important;
}


:deep(.van-popup) {
    z-index: 6005 !important;
}

.anchorSelection {
    width: 100%;
    height: 100vh;
    background-color: #fff;
    box-sizing: border-box;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 6004;

    :deep(.van-icon) {
        color: #fff !important;
    }

    .headers {
        height: 190px;
        background: linear-gradient(180deg, #CDECFF 0%, #FFFFFF 100%);
        border-radius: 0px 0px 0px 0px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: relative;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
            position: static !important;
            z-index: 6004;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    :deep(.van-field__control) {
        padding-right: 50px;
        background-color: transparent !important;
    }

    .product_list_serch-text {
        display: flex;
        align-items: center;
        width: 100%;
        height: 50px;
        position: relative;

        :deep(.van-icon-search) {
            display: none !important;
        }

        .product_list_serch1 {
            display: flex;
            align-items: center;
            background: none;
            width: 100%;
            height: 35px;

            :deep(.van-search__content) {
                height: 35px;
                background-color: #fff;
            }

            :deep(.van-search__field) {
                height: 35px;
            }

            :deep(.van-field__clear) {
                right: 50px !important;
            }
        }

        .product_list_serch2 {
            position: absolute;
            right: 20px;
            display: flex;
            align-items: center;
            justify-content: center;

            :deep(.van-button__text) {
                font-size: 14px;
            }

            .product_list-btn {
                width: 44px;
                height: 26px;
                font-size: 14px;
                color: #ffffff;
                border: none;
                white-space: nowrap;
            }
        }
    }

    .session {
        width: 100%;
        height: 28px;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        padding: 0 15px;

        .session_child {
            width: 76px;
            height: 28px;
            background: #FFFFFF;
            border-radius: 6px 6px 6px 6px;
            border: 1px solid transparent;
            text-align: center;
            line-height: 28px;
            font-weight: 500;
            font-size: 14px;
            color: #666666;
        }

        .session_child_active {
            width: 76px;
            height: 28px;
            background: #FFFFFF;
            border-radius: 6px 6px 6px 6px;
            border: 1px solid #45A6FF;
            text-align: center;
            line-height: 28px;
            font-weight: 500;
            font-size: 14px;
            color: #45A6FF;
        }
    }

    .content {
        width: 100%;
        height: calc(100vh - 270px);
        display: flex;
        align-items: center;

        .content_left {
            width: 90px;
            height: 100%;
            background: #F5F7FA;

            .content_left_child {
                width: 100%;
                height: 44px;
                text-align: center;
                line-height: 44px;
                font-weight: 400;
                font-size: 14px;
                color: #1A1B1C;
            }

            .content_left_child_active {
                width: 100%;
                height: 44px;
                background: #0094FF;
                text-align: center;
                line-height: 44px;
                font-weight: 500;
                font-size: 14px;
                color: #FFFFFF;
            }
        }

        .content_right {
            flex: 1;
            height: 100%;
            box-sizing: border-box;
            padding: 15px;
            overflow: auto;

            .content_right_titte {
                font-weight: 500;
                font-size: 14px;
                color: #222222;
                margin-bottom: 10px;
            }

            .content_right_div {
                width: 100%;
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .shell {
                    width: calc(100% / 3);
                    height: 34px;
                    display: flex;
                    align-items: center;
                    justify-content: flex-start;
                    margin-bottom: 10px;
                    box-sizing: border-box;
                    flex-wrap: wrap;
                }

                .items_top {
                    width: 80px;
                    height: 34px;
                    background: #F6FAFF;
                    border-radius: 4px 4px 4px 4px;
                    border: 1px solid transparent;
                    text-align: center;
                    line-height: 34px;
                    font-weight: 400;
                    font-size: 12px;
                    color: #1A1B1C;
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    justify-content: space-around;

                    img {
                        width: 8px;
                        height: 5px;
                    }
                }

                .items_top_avtive {
                    width: 80px;
                    height: 34px;
                    background: #F6FAFF;
                    border-radius: 4px 4px 4px 4px;
                    border: 1px solid #0094FF;
                    text-align: center;
                    line-height: 34px;
                    font-weight: 400;
                    font-size: 12px;
                    color: #40AFFF;
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    justify-content: space-around;

                    img {
                        width: 8px;
                        height: 5px;
                    }
                }

                .apprentice {
                    font-weight: 500;
                    font-size: 12px;
                    color: #999999;
                    width: calc(100% / 3);
                    text-align: center;
                    margin-bottom: 5px;
                }

                .apprenticeAvtive {
                    font-weight: 500;
                    font-size: 12px;
                    color: #45A6FF;
                    width: calc(100% / 3);
                    text-align: center;
                    margin-bottom: 5px;
                }

            }
        }
    }

    .bottom {
        width: 70px;
        width: 100%;
        box-sizing: border-box;
        padding: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .cancel {
            width: 118px;
            height: 46px;
            background: #F7F8FA;
            border-radius: 10px 10px 10px 10px;
            border: 1px solid #F7F8FA;
            font-weight: 500;
            font-size: 15px;
            color: #1D2129;
            text-align: center;
            line-height: 46px;
        }

        .submit {
            width: 213px;
            height: 46px;
            background: linear-gradient(90deg, #0B9BFB 0%, #198CFE 100%);
            border-radius: 10px 10px 10px 10px;
            border-image: linear-gradient(90deg, rgba(11, 155, 251, 1), rgba(25, 140, 254, 1)) 1 1;
            font-weight: 500;
            font-size: 15px;
            color: #FFFFFF;
            text-align: center;
            line-height: 46px;
        }
    }
}
</style>